package es.ats.codington.festival.servlets;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

import es.ats.codington.festival.domain.Event;
import es.ats.codington.festival.domain.Image;
import es.ats.codington.festival.domain.Place;
import es.ats.codington.festival.domain.Visitor;
import es.ats.codington.festival.services.EventService;
import es.ats.codington.festival.services.ImageService;
import es.ats.codington.festival.services.VisitorService;

@MultipartConfig
public class PresentNewEventServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	/**
     * Utility method to get file name from HTTP header content-disposition
     */
    private String getFileName(Part part) {
        String contentDisp = part.getHeader("content-disposition");
        String[] tokens = contentDisp.split(";");
        for (String token : tokens) {
            if (token.trim().startsWith("filename")) {
                return token.substring(token.indexOf("=") + 2, token.length()-1);
            }
        }
        return "";
    }
    
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		RequestDispatcher requestDispatcher = request.getRequestDispatcher("jsp/newEvent.jsp");
        requestDispatcher.forward(request, response);
		
        
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Visitor visitor = new Visitor();
		VisitorService vs = new VisitorService();
		Event event = new Event();
		EventService es = new EventService();
		Place place = new Place();
		ImageService is = new ImageService();
		Image img = new Image();
		try {
			
			HttpSession sesion = request.getSession(false);
			int peopleId = (Integer) sesion.getAttribute("peopleid");						
			visitor=vs.getVisitorById(peopleId);
			if(visitor.getAdmin())
			{								
				Part filePart = request.getPart("image");
				String imageName = getFileName(filePart);
				String[] splitedName=imageName.split("\\.(?=[^\\.]+$)");
				String imageType=splitedName[1];
				BufferedImage imBuff = ImageIO.read(filePart.getInputStream());
				img.setPhoto(imBuff);
				img.setType(imageType);
				int photoId=is.insertImage(img);
				
			    if (photoId==0){
			    	request.setAttribute("error", "Something were wrong inserting the image. Please try again in a few minits.");
					RequestDispatcher requestDispatcher = request.getRequestDispatcher("jsp/error.jsp");
			        requestDispatcher.forward(request, response);
			    }
			    else{
			    	String name = request.getParameter("name");
					String description = request.getParameter("description");
					String dateparam= request.getParameter("start");
					String[] splitedDate=dateparam.split(" ");
					String[] splitedHour=splitedDate[1].split(":");
					int newHour=Integer.parseInt(splitedHour[0]);
					if (splitedDate[2].compareToIgnoreCase("PM")==0){
						newHour=newHour+12;
						if (newHour==24){
							newHour=12;
						}
					}
					else{
						if (newHour==12){
							newHour=00;
						}
					}
					String start=splitedDate[0]+" "+newHour+":"+splitedHour[1];
					DateFormat format = new SimpleDateFormat("MM/dd/yyyy hh:mm");
					Date date = format.parse(start);
					int placeId = Integer.parseInt(request.getParameter("place"));
					int duration = Integer.parseInt(request.getParameter("duration"));
					float price = Float.parseFloat(request.getParameter("price"));
					event.setName(name);
					event.setDescription(description);
					event.setStart(date);
					place.setPlaceId(placeId);
					event.setPlace(place);
					event.setDuration(duration);
					event.setPrice(price);
					event.setPhotoId(photoId);
					int affectedRows=es.insertEvent(event);
					if (affectedRows==0){
						request.setAttribute("error", "Something were wrong inserting the event. Please try again in a few minits.");
						RequestDispatcher requestDispatcher = request.getRequestDispatcher("jsp/error.jsp");
				        requestDispatcher.forward(request, response);
					}
					else{
						List<Event> events = new ArrayList<Event>();
						events=es.getAllEvents();
						request.setAttribute("allevents",events);
						request.setAttribute("eventsize",events.size());
						RequestDispatcher requestDispatcher = request.getRequestDispatcher("jsp/adminEvents.jsp");
				        requestDispatcher.forward(request, response);
					}
				}
			}
			
			else
			{
				request.setAttribute("error", "Only the admins can add new events");
				RequestDispatcher requestDispatcher = request.getRequestDispatcher("jsp/error.jsp");
		        requestDispatcher.forward(request, response);	
			}


			
		} catch (Exception e) {
			request.setAttribute("error", "Something were wrong during the process. Please, try it again in a few minutes.");
			RequestDispatcher requestDispatcher = request.getRequestDispatcher("jsp/error.jsp");
	        requestDispatcher.forward(request, response);			
		}
	}
}